/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package plugin;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;

/**
 * Loading System Class
 * @author zem
 */
public class SystemClassLoader {

    SystemInterface instance;

    public SystemClassLoader(String jarname) {

        File pluginDir = new File("lib");

        File jar = new File("" + pluginDir + File.separatorChar + jarname);


        //run plugins

        Class pluginClass = null;


        try {
            URL jarURL = jar.toURI().toURL();
            URLClassLoader classLoader = new URLClassLoader(new URL[]{jarURL});
            //reading MANIFEST in try to find main class
            
            String mainclass = getMainClassName(jarURL);
            boolean mainclass_found = false;
           if(mainclass!=null){ mainclass_found = true;}



            if (mainclass_found) { //if main class has been found
                //start
                pluginClass = classLoader.loadClass(mainclass);
                instance = (SystemInterface) pluginClass.newInstance();
                instance.start();
            } else {
                System.out.println("cannot find main class");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println(e);
        }

    }

    public void Interrupt() {
        try {
            instance.interrupt();
        } catch (Exception er) {
        }
    }

    public String getMainClassName(URL jarURL) throws IOException { //getting main class
        jarURL = new URL("jar", "", jarURL + "!/");
        JarURLConnection uc = (JarURLConnection) jarURL.openConnection();
        Attributes attr = uc.getMainAttributes();
      
        String p = attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
        
        return p;
    }
}
